ROOT=$(pwd)
SCRIPT_DIR=$ROOT/scripts
HARMONY_DIR=$ROOT/harmony
OUTPUT_DIR=$ROOT/outputs

# 删除文件
function remove() {
    if [ -e $1 ]
        then
        rm -rf $1
        echo "[INFO] File $1 is removed"
    else 
        echo "[WARNNIG] File $1 is not exist"
    fi
}

# 设置变量
function setVar() {
    local varName=$1
    local varValue=$2
    eval "$varName=$varValue"
}

# 执行命令（报错抛出错误信息后中断脚本）
function commandErrorMessage() {
    local commands=("$@")  # 将所有传入的参数作为命令存储在一个数组中
    local errorMessage=${commands[-1]}  # 最后一个参数作为错误信息
    unset commands[-1]  # 移除最后一个参数（错误信息），只保留命令

    for command in "${commands[@]}"; do
        $command
        if [ $? -ne 0 ]; then
            restore
            echo "[ERROR] $errorMessage"
            echo "[INFO] Check $LOG_FILE for more details"
            exit 1
        fi
    done
}

# 构建前端工程
function runFront() {
    echo "[INFO] Building front-end project..."
    commandErrorMessage "cd $ROOT" "npm run redev" "Failed to build front-end project"
}


# 清原生缓存
function clearCache() {
    echo "[INFO] hvigorw clean"
    commandErrorMessage "cd $HARMONY_DIR" "hvigorw clean" "Failed to clean."
    commandErrorMessage "cd $HARMONY_DIR" "remove $HARMONY_DIR/entry/.cxx" "Failed to remove $HARMONY_DIR/entry/.cxx"
    commandErrorMessage "cd $HARMONY_DIR" "remove $HARMONY_DIR/entry/oh_modules" "Failed to remove $HARMONY_DIR/entry/oh_modules"
    commandErrorMessage "cd $HARMONY_DIR" "remove $HARMONY_DIR/oh_modules" "Failed to remove $HARMONY_DIR/oh_modules"
}

# 文件还原
function restore() {
    echo "[INFO] Restoring environment..."
    node $SCRIPT_DIR/change-cmakelists.js debug 
    node $SCRIPT_DIR/change-har-path.js debug
    echo "[INFO] Environment restored"
}

# ohpm install
function ohpmInstall() {
    echo "[INFO] Installing dependencies..."
    commandErrorMessage "cd $HARMONY_DIR" "ohpm install" "Failed to install dependencies."
    commandErrorMessage "cd $ROOT" "npm run codegen" "Failed to generate code."
    echo "[INFO] Dependencies installed"
}

# 打debug包
function runDebug() {
    echo "[INFO] Building debug package..."
    # 清缓存
    clearCache
    # 把oh-package的path修改为react_native_openharmony.har
    commandErrorMessage "node $SCRIPT_DIR/change-har-path.js debug" "Failed to change har package path to debug."
    # 装依赖
    ohpmInstall
    # 修改build-profile.json5的CMakeLists路径为CMakeLists-debug.txt
    commandErrorMessage "node $SCRIPT_DIR/change-cmakelists.js debug" "Failed to change CMakeLists path."
    # 出hap包
    commandErrorMessage "cd $HARMONY_DIR" "hvigorw --mode module -p module=entry@default -p product=default -p buildMode=debug -p requiredDeviceType=phone assembleHap --analyze=normal --parallel --incremental --no-daemon" "Failed to build debug har."
    # 归档
    commandErrorMessage "mv $HARMONY_DIR/entry/build/default/outputs/default/entry-default-signed.hap $OUTPUT_DIR/entry-debug.hap" "Failed to move entry-debug.hap to $OUTPUT_DIR"
    # 回退环境
    restore
    echo "[INFO] Debug har is built successfully"
}

# 打release包
function runRelease() {
    echo "[INFO] Building release package..."
    # 清缓存
    clearCache
    # 把oh-package的path修改为react_native_openharmony_release.har
    commandErrorMessage "node $SCRIPT_DIR/change-har-path.js release" "Failed to change har package path to release."
    # 装依赖
    ohpmInstall
    # 修改build-profile.json5的CMakeLists路径为CMakeLists-release.txt
    commandErrorMessage "node $SCRIPT_DIR/change-cmakelists.js release" "Failed to change CMakeLists path." 
    # 出hap包
    commandErrorMessage "cd $HARMONY_DIR" "hvigorw --mode module -p module=entry@default -p product=default -p buildMode=release -p requiredDeviceType=phone assembleHap --analyze=normal --parallel --incremental --no-daemon" "Failed to build release har."
    # 归档
    commandErrorMessage "mv $HARMONY_DIR/entry/build/default/outputs/default/entry-default-signed.hap $OUTPUT_DIR/entry-release.hap" "Failed to move entry-release.hap to $OUTPUT_DIR"
    # 回退环境
    restore
    echo "[INFO] Release har is built successfully"
}

# 构建
function build() {
    case $1 in
        js)
            runFront
            ;;
        debug)
            runDebug
            ;;
        release)
            runRelease
            ;;
        *)
            echo "[ERROR] Invalid argument: $1"
            ;;
    esac
    echo "[INFO] Build completed"
}

# 生成日志记录
mkdir -p $OUTPUT_DIR
mkdir -p $OUTPUT_DIR/log
LOG_FILE=$OUTPUT_DIR/log/build-$(date +"%Y%m%d%H%M%S").log
truncate -s 0 $LOG_FILE
exec > >(tee -a $LOG_FILE) 2> >(tee -a $LOG_FILE >&2)

argList="js debug release"
if [ "$#" -ge 1 ]
    then
    argList=$@
fi

for arg in $argList; do
    build $arg
done